package org.iwidget.desktop.core;
import org.iwidget.desktop.model.*;
import org.iwidget.desktop.ui.*;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
 *
 * @author Muhammad Hakim A
 */


public class IwidgetMethods
{
    static class RunThread extends Thread
    {

        @Override
        public void run()
        {
            String result = IwidgetMethods.runInternal(cmd);
            widget.getIwidgetData().runResult = result;
            widget.triggerEvent("onRunInBgComplete");
        }

        WidgetElement widget;
        String cmd;

        public RunThread(WidgetElement widget, String cmd)
        {
            this.widget = widget;
            this.cmd = cmd;
        }
    }


    public IwidgetMethods()
    {
        IwidgetMethods.parent = parent;
    }

    public static long currentTimeMillis()
    {
        return System.currentTimeMillis();
    }

    public static void alert(final WidgetElement widget, final String text)
    {
        (new Thread() {

            public void run()
            {
                IwidgetMethods.disableUpdates(widget);
                JOptionPane.showMessageDialog(new JFrame(), text, "Alert", 1);
                IwidgetMethods.enableUpdates(widget);
            }

        }).start();
    }

    public static int question(WidgetElement widget, String question, String buttons)
    {
        int option = 2;
        if(buttons.equals("YesNo"))
            option = 0;
        else
        if(buttons.equals("YesNoCancel"))
            option = 1;
        disableUpdates(widget);
        int result = JOptionPane.showConfirmDialog(new JFrame(), question, "Question", option);
        enableUpdates(widget);
        return result;
    }

    public static String input(WidgetElement widget, String title, String prompt)
    {
        disableUpdates(widget);
        String result = JOptionPane.showInputDialog(new JFrame(), title, prompt, 3);
        enableUpdates(widget);
        return result;
    }

    public static void beep()
    {
        Toolkit.getDefaultToolkit().beep();
    }

    public static String escape(String s)
    {
        try{
            return URLEncoder.encode(s, "UTF-8");
        }catch(Exception e){
            return s;
        }
    }

    public static String unescape(String s)
    {
        try{
            return URLDecoder.decode(s, "UTF-8");
        }catch(Exception e){
            return s;
        }
    }

    public static int random()
    {
        int start = 0;
        int end = 0x10000;
        return (int)((double)(end - start) * Math.random()) + start;
    }

    public static int random(int end)
    {
        int start = 0;
        return (int)((double)(end - start) * Math.random()) + start;
    }

    public static int random(int start, int end)
    {
        return (int)((double)(end - start) * Math.random()) + start;
    }

    public static void closeWidget(WidgetElement widget)
    {
        widget.getParent().closeWidget(widget.getWindowJS().getTitle());
    }

    public static void showWidgetPreferences(WidgetElement widget)
    {
        widget.getUIComponent().showPreferences();
    }

    public static void savePreferences(WidgetElement widget)
    {
        widget.triggerEvent("onPreferencesChanged");
    }

    public static void sleep(long time)
    {
        try
        {
            Thread.sleep(time);
        }
        catch(Exception e) { }
    }

    public static void debug(WidgetElement widget, String debugType, String message)
    {
        boolean printItem = false;
        if(widget.getDebug().equals("all"))
            printItem = true;
        else
        if(widget.getDebug().indexOf("status") > -1 && debugType.equals("Status"))
            printItem = true;
        else
        if(widget.getDebug().indexOf("warnings") > -1 && debugType.equals("Warning"))
            printItem = true;
        else
        if(widget.getDebug().indexOf("errors") > -1 && debugType.equals("Error"))
            printItem = true;
        if(printItem)
            widget.getParent().getDebugFrame().addText(widget.getWindowJS().getTitle() + ":" + debugType + ":" + message);
    }

    public static String[] form(WidgetElement widget, ElementPreferences formFields[], String title, String saveLabel, String cancelLabel)
    {
        String result = FormFrame.getForm(widget, formFields, title, saveLabel, cancelLabel);
        if(result.equals("Save"))
        {
            String output[] = new String[formFields.length];
            for(int iCtr = 0; iCtr < formFields.length; iCtr++)
                output[iCtr] = formFields[iCtr].getValue();

            return output;
        } else
        {
            return null;
        }
    }

    public static void openURL(String data)
    {
        try
        {
            BrowserLauncher.openURL(data);
        }
        catch(Exception e)
        {
            parent.getDebugFrame().addText("SYSTEM:Error:openURL failed to open: " + data);
        }
    }

    public static void focusWidget(WidgetElement widget)
    {
        if(widget.getUIComponent() != null)
            widget.getUIComponent().requestFocus();
    }

    public static void updateNow(WidgetElement widget)
    {
        if(widget.getUIComponent() != null)
        {
            if(widget.getWindowJS().hasChanged())
            {
                widget.getUIComponent().setSize(widget.getWindowJS().getWidth(), widget.getWindowJS().getHeight());
                widget.getUIComponent().setLocation(widget.getWindowJS().getX(), widget.getWindowJS().getY());
                widget.getUIComponent().maketrans();
                widget.getWindowJS().clearChange();
            }
        } else
        {
            widget.getUIComponent().repaint();
        }
    }

    public static void disableUpdates(WidgetElement widget)
    {
        if(widget.getUIComponent() != null)
            widget.getUIComponent().enableRepaint(false);
    }

    public static void enableUpdates(WidgetElement widget)
    {
        if(widget.getUIComponent() != null)
            widget.getUIComponent().enableRepaint(true);
    }

    public static String run(String cmd)
    {
        return runInternal(cmd);
    }

    public static void runInBg(WidgetElement widget, String cmd)
    {
        RunThread rt = new RunThread(widget, cmd);
        rt.start();
    }

    public static String runInternal(String cmd)
    {
        StringBuffer sb = new StringBuffer();
        try
        {
            String fullCmd = cmd;
            if(System.getProperty("os.name").startsWith("Windows"))
                fullCmd = "cmd /c " + cmd;
            Process p = Runtime.getRuntime().exec(fullCmd);
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            for(String s = reader.readLine(); s != null; s = reader.readLine())
                sb.append(s).append('\n');

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return sb.toString();
    }

    private static Iwidget parent;
}